#include "TetrisBlock.h"
#include "TetrisGame.h"
#include "TetrisBoard.h"

TetrisBlock::TetrisBlock(TetrisGame* game)
	: game_(game),
	pos_(4,0)
{
}


TetrisBlock::~TetrisBlock(void)
{
	Release();
}


/**
@brief 테트리스 Block 설정한다
@date 2013/01/24
@author 임진영(deviak@deviak.com)
@return void
*/
void TetrisBlock::Init()
{
	int block_list[kBlockTypeMax][kBlockHeight][kBlockWidth] = {		
		{{0,1,0,0},
		{0,1,0,0},
		{0,1,0,0},
		{0,1,0,0}},
		{{0,0,0,0},
		{0,1,1,0},
		{0,1,1,0},
		{0,0,0,0}}};

		for(int i=0; i<kBlockTypeMax; ++i)
			for(int j=0; j<kBlockHeight; ++j)
				for(int k=0; k<kBlockWidth; ++k)
					block_list_[i][j][k] = block_list[i][j][k];

		int block[kBlockHeight][kBlockWidth] = {{0,0,0,0},
		{0,1,1,0},
		{0,1,1,0},
		{0,0,0,0}};

		for(int i=0; i<kBlockHeight; ++i)
			for(int j=0; j<kBlockWidth; ++j)
				block_[i][j] = block[i][j];
}

/**
@brief 테트리스 블록 출력한다
@date 2013/01/24
@author 임진영(deviak@deviak.com)
@return void
*/
void TetrisBlock::Render()
{
	MoveCursor(POSITION(pos_.y_,pos_.x_));
	
	for(int i=0; i<kBlockHeight; ++i)
		for(int j=0; j<kBlockWidth; ++j)
			if( block_[i][j] )
				DrawObject(POSITION(pos_.x_+j,pos_.y_+i), 'O' );
}

/**
@brief 메모리 해제
@date 2013/01/24
@author 임진영(deviak@deviak.com)
@return void
*/
void TetrisBlock::Release()
{
	game_ = NULL;
}

/**
@brief 랜덤으로 테트리스 Block을 생성한다
@date 2013/01/24
@author 임진영(deviak@deviak.com)
@return bool
*/
bool TetrisBlock::CreateBlock()
{
	int i,j;
	int block_type;

	pos_ = POSITION(4,0);

	Randomize();
	block_type = Random(kBlockTypeMax);

	for(i=0; i<4; i++){
		for(j=0; j<4; j++){
			block_[i][j]=0;
			block_[i][j]=block_list_[block_type][i][j];
		}
	}
	return false;
}

/**
@brief Block을 회전시킨다
@date 2013/01/24
@author 임진영(deviak@deviak.com)
@return bool
*/
bool TetrisBlock::TurnBlock()
{
	int i,j;
	int tmp[4][4]={0};

	for(i=0; i<4; i++){
		for(j=0; j<4; j++){
			tmp[i][j]=block_[i][j];
		}
	}

	for(i=0; i<4; i++){
		for(j=0; j<4; j++){
			block_[i][j]=tmp[3-j][i];
		}
	}
	if(game_->CheckOver(pos_)){
		for(i=0; i<4; i++){
			for(j=0; j<4; j++){
				block_[i][j]=tmp[i][j];
			}
		}
		return true;
	}

	if(game_)
	{
		TetrisBoard* pBoard = game_->Board();
		if(pBoard)
		{
			int* board = pBoard->Board();

			for(i=0; i<4; i++){
				for(j=0; j<4; j++){
					board[((pos_.y_+i)*TetrisBoard::kTetrisBoardWidth)+(pos_.x_+j)]-=tmp[i][j];
					board[((pos_.y_+i)*TetrisBoard::kTetrisBoardWidth)+(pos_.x_+j)]+=block_[i][j];
				}
			}
		}
	}
	

	return false;
}

/**
@brief Block을 이동시킨다
@date 2013/01/24
@author 임진영(deviak@deviak.com)
@return void
*/
void TetrisBlock::MoveBlock(const POSITION &p)
{
	pos_ = p;

	if(game_)
	{
		TetrisBoard* pBoard = game_->Board();
		if(pBoard)
		{
			pBoard->MoveBlock(p, Block());
		}
	}
	
}